// component/share-dialog/share-dialog.js
const app = getApp();
const api = require("../../server/Api.js");
const util = require("../../utils/util.js");
Component({
  options: {
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    fromPage: String,
    model: Object
  },

  /**
   * 组件的初始数据
   */
  data: {
    showShareImage: false,
    imagePath: ""
  },

  /**
   * 组件的方法列表
   */
  methods: {
    hiddenDialog: function() {
      this.triggerEvent('hiddenShareDialog')
    },
    shareByWechat: function() {
      tt.showShareMenu();
      this.triggerEvent('hiddenShareDialog')
    },
    hiddenShareImageDialog: function() {
      var that = this;
      that.setData({
        showShareImage: false
      })
    },
    shareByInfo: function() {
      // tt.navigateTo({
      //   url: '../test/test',
      // })
      // return;
      var that = this;
      that.setData({
        showShareImage: true
      })
      tt.showLoading({
        title: '生成海报中...',
      })
      if (that.data.fromPage === "index") {
        that.createIndexShareImg();
      } else if (that.data.fromPage === "goods") {
        that.createGoodsShareImg();
      }

    },
    //绘制首页分享图片
    createIndexShareImg: function(imageList) {
      var that = this;
      console.log(that.data.model)
      let drawCount = 1;
      let drawAll = 29;
      var context = tt.createCanvasContext('mycanvas', that);
      tt.downloadFile({
        url: "https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/bg.png",
        success(res) {
          console.log(res)
          context.drawImage(res.tempFilePath, 0, 0, 375, 667);
          context.draw(false, () => {
            that.saveTempImage(drawCount++, drawAll);
          });
          let logoUrl = "https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/logo.png";
          if (that.data.model.images && that.data.model.images.indexOf("https://") != -1) {
            logoUrl = that.data.model.images
          }
          tt.downloadFile({
            url: logoUrl,
            success(res) {
              context.save();
              that.roundRect(context, 162, 29, 52, 52, 10);
              context.setFillStyle('white')
              context.fillRect(162, 29, 52, 52)
              context.drawImage(res.tempFilePath, 163, 30, 50, 50);
              context.restore();
            }
          })
          context.setFontSize(16);
          context.setFillStyle('white');
          context.setTextAlign('center');
          context.font = 'normal bold 16px PingFangSC-Semibold';
          context.fillText(that.data.model.storeName, 187, 107);
          context.setFontSize(14);
          context.setFillStyle('white');
          context.setTextAlign('center');
          context.font = 'normal normal 14px PingFangSC-Regular';
          context.fillText(that.data.model.address, 187, 131);
          context.save();
          that.roundRect(context, 12, 146, 351, 400, 20);
          context.setFillStyle('white')
          context.fillRect(12, 146, 351, 400);
          context.restore();
          context.draw(true, () => {
            that.saveTempImage(drawCount++, drawAll);
          });
          tt.downloadFile({
            url: "https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/jrbg.png",
            success(res) {
              context.drawImage(res.tempFilePath, 148, 166, 80, 20);
              context.draw(true, () => {
                that.saveTempImage(drawCount++, drawAll);
              });
            }
          })
          let param = {
            pageNumber: 1,
            pageSize: 8,
            storeId: that.data.model.id,
            companyId: app.globalData.companyId,
            platformId: app.globalData.platformId,
          }
          api.queryHomeGoods(param).then(res => {
            drawAll = drawAll - 24 + res.records.length * 3
            for (let i = 0; i < res.records.length; i++) {
              let x = i % 2 == 0 ? 24 : 199;
              let y = 210 + parseInt(i / 2) * 84;
              setTimeout(function() {
                app.downloadFile(res.records[i].spu_image + "?x-image-process=image/resize,m_pad,w_60,h_60").then(res => {
                  context.save();
                  context.beginPath()
                  context.arc(x + 30, y + 30, 30, 0, 2 * Math.PI) //画出圆
                  context.strokeStyle = "#fff";
                  context.clip();
                  context.drawImage(res.tempFilePath, x, y, 60, 60);
                  context.restore();
                  context.draw(true, () => {
                    that.saveTempImage(drawCount++, drawAll);
                  });
                }).catch(res => {
                  app.showToast("下载图片失败")
                  drawCount++;
                })
              }, i * 250)
              that.fillTextEclip(context, res.records[i].title, x + 92 - 24, y + 9, 84, 12, 16, "normal", "PingFangSC-Regular");
              context.setFontSize(12);
              context.setFillStyle('#E93324');
              context.setTextAlign('left');
              context.font = 'normal bold 12px PingFangSC-Semibold';
              context.fillText("￥", x + 92 - 24, y + 54);
              context.setFontSize(18);
              context.setFillStyle('#E93324');
              context.setTextAlign('left');
              context.font = 'normal bold 18px PingFangSC-Semibold';
              context.fillText(res.records[i].sale_price, x + 102 - 24, y + 54);
              let priceWidth = 14 * (res.records[i].sale_price + "").length
              context.draw(true, () => {
                that.saveTempImage(drawCount++, drawAll);
              });

              context.setFontSize(12);
              context.setFillStyle('#999');
              context.setTextAlign('left');
              context.font = 'normal normal 12px PingFangSC-Regular';
              context.fillText("￥", x + 102 + priceWidth - 10 - 24, y + 54);
              context.fillText(res.records[i].maket_price, x + 102 + priceWidth - 24, y + 54);
              let priceWidth1 = 6 * (res.records[i].maket_price + "").length
              context.moveTo(x + 102 + priceWidth - 10 - 24, y + 50)
              context.lineTo(x + 102 + priceWidth - 24 + 3 + priceWidth1, y + 50)
              context.setStrokeStyle('#999')
              context.stroke();
              context.draw(true, () => {
                that.saveTempImage(drawCount++, drawAll);
              });
            }
          }).catch(msg => {
            app.showToast("获取推荐商品失败!")
            tt.hideLoading();
            that.setData({
              showShareImage: false
            });
          })
          let userId = "";
          let userBean = app.globalData.userBean;
          if (userBean && userBean.consumerId) {
            userId = userBean.consumerId
          }
          api.getShareInfo(userId, 1, that.data.model.id).then(res => {
            app.downloadFile(res.url + "?x-image-process=image/resize,m_pad,w_180,h_180").then(res => {
              console.log(res);
              context.save();
              context.beginPath()
              context.arc(153 + 35, 562 + 35, 35, 0, 2 * Math.PI) //画出圆
              context.strokeStyle = "#fff";
              context.clip();
              context.drawImage(res.tempFilePath, 153, 562, 70, 70);
              context.restore();
              context.draw(true, () => {
                that.saveTempImage(drawCount++, drawAll);
              });
            }).catch(res => {
              tt.hideLoading();
              app.showToast("下载分享二维码失败!")
              that.setData({
                showShareImage: false
              });
            })
          }).catch(msg => {
            app.showToast("获取分享二维码失败!")
            tt.hideLoading();
            that.setData({
              showShareImage: false
            });
          })
          context.font = 'normal normal 10px PingFangSC-Regular';
          context.setFontSize(10);
          context.setFillStyle('white');
          context.setTextAlign('left');
          context.fillText("长按图片识别，更多爆款抢先加购", 113, 647);
          context.draw(true, () => {
            that.saveTempImage(drawCount++, drawAll);
          });
        },
        fail(res) {
          console.log(res)
        }
      })
    },
    //绘制商品详情分享图片
    createGoodsShareImg() {
      var that = this;
      console.log(that.data.model)
      let drawCount = 1;
      let drawAll = 8;
      that.setData({
        imagePath: ""
      });
      var context = tt.createCanvasContext('mycanvas', that);
      context.setFillStyle("#ffffff")
      context.fillRect(0, 0, 375, 667);
      app.downloadFile("https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/logo.png").then(res => {
        context.drawImage(res.tempFilePath, 12, 24, 40, 40);
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }).catch(res => {
        app.showToast("下载图片失败")
        drawCount++;
      })
      context.save();
      context.setFontSize(14);
      context.setFillStyle('#434343');
      context.font = 'normal normal 14px PingFangSC-Light';
      context.fillText("邻里一起拼", 60, 38);
      context.fillText("同享批发价", 60, 60);
      context.restore();
      app.downloadFile("https://obs.cn-north-1.myhuaweicloud.com/obs-7d37/hh_shequ/hoshii.png").then(res => {
        context.drawImage(res.tempFilePath, 170, 8, 193, 72);
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }).catch(res => {
        app.showToast("下载图片失败")
        drawCount++;
      })
      app.downloadFile(that.data.model.images[0].url.split('?')[0] + "?x-image-process=image/resize,m_pad,w_351,h_351").then(res => {
        context.save();
        that.roundRect(context, 12, 88, 351, 351, 10);
        context.setFillStyle('white')
        context.fillRect(12, 88, 351, 351)
        context.drawImage(res.tempFilePath, 12, 88, 351, 351);
        context.restore();
        context.draw(true, () => {
          that.saveTempImage(drawCount++, drawAll);
        });
      }).catch(res => {
        app.showToast("下载图片失败")
        drawCount++;
      })
      context.save();
      that.fillTextEclip(context, that.data.model.title, 12, 472, 224, 16, 22, "bold", "PingFangSC-Semibold");
      context.restore();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });
      let tagLeft = 0;
      for (let m = 0; m < that.data.model.tags.length; m++) {
        let tag = that.data.model.tags[m].tagName;
        let tagLength = tag.length * 10;
        context.save();
        context.beginPath()
        context.arc(tagLeft + 12 + 7, 511 + 7, 7, 0.5 * Math.PI, 1.5 * Math.PI)
        context.setStrokeStyle('#E93324')
        context.stroke()
        context.moveTo(tagLeft + 12 + 7, 511)
        context.lineTo(tagLeft + 12 + 7 + tagLength, 511)
        context.setStrokeStyle('#E93324')
        context.stroke()
        context.moveTo(tagLeft + 12 + 7, 511 + 14)
        context.lineTo(tagLeft + 12 + 7 + tagLength, 511 + 14)
        context.setStrokeStyle('#E93324')
        context.stroke()
        context.beginPath()
        context.arc(tagLeft + 12 + 7 + tagLength, 511 + 7, 7, 1.5 * Math.PI, 0.5 * Math.PI)
        context.setStrokeStyle('#E93324')
        context.stroke()
        context.setFontSize(10);
        context.setFillStyle('#E93324');
        context.font = 'normal normal 10px PingFangSC-Regular';
        context.fillText(tag, tagLeft + 12 + 7, 522);
        tagLeft += 14 + tagLength + 4;
        context.restore();
      }
      context.save();
      context.setFontSize(20);
      context.font = 'normal bold 20px PingFangSC-Semibold';
      context.setFillStyle('#E93324');
      context.fillText("￥", 12, 572);
      context.font = 'normal bold 40px PingFangSC-Semibold';
      context.setFontSize(40);
      context.fillText(that.data.model.minPrice, 30, 572);
      let priceWidth = 26 * (that.data.model.minPrice + "").length - 13
      if ((that.data.model.minPrice + "").indexOf(".") === -1) {
        priceWidth = priceWidth + 13
      }
      context.restore();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });
      context.save();
      context.font = 'normal normal 14px PingFangSC-Regular';
      context.setFillStyle('#999');
      context.setFontSize(14);
      context.fillText("￥", 20 + priceWidth + 10, 572);
      context.fillText(that.data.model.maxPrice, 20 + priceWidth + 20, 572);
      let priceWidth1 = 7 * (that.data.model.maxPrice + "").length
      context.moveTo(20 + priceWidth + 12, 568)
      context.lineTo(20 + priceWidth + 17 + priceWidth1, 568)
      context.setStrokeStyle('#999')
      context.stroke();
      context.restore();
      context.save();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });
      that.roundRect(context, 12, 597, 351, 36, 5);
      context.setFillStyle('#FCEDEC')
      context.fillRect(12, 597, 351, 36)
      context.restore();
      context.save();
      context.setFontSize(12);
      context.setFillStyle('#333333');
      context.font = 'normal 12px PingFangSC-Regular';
      context.fillText("长按识别小程序码了解商品详情", 103, 620);
      context.restore();
      context.draw(true, () => {
        that.saveTempImage(drawCount++, drawAll);
      });
      let userId = "";
      let userBean = app.globalData.userBean;
      if (userBean && userBean.consumerId) {
        userId = userBean.consumerId
      }
      api.getShareInfo(userId, 2, that.data.model.spuId).then(res => {
        app.downloadFile(res.url + "?x-image-process=image/resize,m_pad,w_180,h_180").then(res => {
          console.log(res);
          context.save();
          context.beginPath()
          context.arc(304, 514, 59, 0, 2 * Math.PI) //画出圆
          context.strokeStyle = "#fff";
          context.clip();
          context.drawImage(res.tempFilePath, 245, 455, 118, 118);
          context.restore();
          context.draw(true, () => {
            that.saveTempImage(drawCount++, drawAll);
          });
        }).catch(res => {
          tt.hideLoading();
          app.showToast("下载分享二维码失败!")
          that.setData({
            showShareImage: false
          });
        })
      }).catch(msg => {
        tt.hideLoading();
        app.showToast("获取分享二维码失败!")
        that.setData({
          showShareImage: false
        });
      })
    },
    saveTempImage(drawCount, drawAll, forceDraw) {
      console.log("saveTempImage", drawCount, drawAll, forceDraw);
      let that = this;
      if (drawCount == drawAll || forceDraw) {
        setTimeout(() => {
          tt.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: function(res) {
              var tempFilePath = res.tempFilePath;
              that.setData({
                imagePath: tempFilePath
              });
              tt.hideLoading();
            },
            fail: function(res) {
              console.log("生成海报失败", res);
              tt.showToast({
                title: '生成海报失败',
                icon: "none"
              })
              tt.hideLoading();
              that.setData({
                showShareImage: false
              });
            }
          }, that);
        }, 600)
      }
    },
    //圆角
    roundRect(ctx, x, y, w, h, r) {
      ctx.beginPath()
      ctx.setStrokeStyle('transparent')
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
      ctx.stroke()
      ctx.closePath()
      ctx.clip()
    },

    //文字截取
    fillTextEclip(context, text, x, y, w, fontSize, lineHeight, fontWeight, fontFamily) {
      var chr = text.split("");
      var temp = "";
      var row = [];
      context.setFontSize(fontSize)
      context.setFillStyle("#333")
      context.font = 'normal ' + fontWeight + ' ' + fontSize + 'px ' + fontFamily;
      context.setTextAlign("left")
      for (var a = 0; a < chr.length; a++) {
        if (context.measureText(temp).width <= w) {
          temp += chr[a];
        } else {
          row.push(temp);
          temp = chr[a];
        }
      }
      row.push(temp);
      if (row.length > 2) {
        var rowCut = row.slice(0, 2);
        var rowPart = rowCut[1];
        var test = "";
        for (var a = 0; a < rowPart.length; a++) {
          if (context.measureText(test).width > (w - fontSize)) {
            break;
          }
          test += rowPart[a];
        }
        rowCut.splice(1, 1, test + "...");
        row = rowCut;
      }
      for (var b = 0; b < row.length; b++) {
        context.setFontSize(fontSize)
        context.setFillStyle("#333")
        context.font = 'normal ' + fontWeight + ' ' + fontSize + 'px ' + fontFamily;
        context.setTextAlign("left")
        context.fillText(row[b], x, y + parseInt((lineHeight - fontSize) / 2) + b * lineHeight, w);
      }
    },

    //点击保存到相册
    saveShareImage: function() {
      var that = this
      util.ttAuth('scope.writePhotosAlbum', function() {
        tt.saveImageToPhotosAlbum({
          filePath: that.data.imagePath,
          success(res) {
            tt.showToast({
              title: '图片已保存到相册'
            })
            that.triggerEvent('hiddenShareDialog');
          },
          fail(res) {
            app.showToast("保存到相册失败")
          }
        })
      });
    }
  }
})